﻿using Scap.Info;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Scap.Core
{
    public class DeviceTaskHandlerConnect : DeviceTaskHandler
    {




        public DeviceTaskHandlerConnect(Info.DeviceTaskModel model)
            : base(model)
        {

        }

        public override void Run()
        {
            ConnectToDevice();
        }


        private void ConnectToDevice()
        {

            try
            {
                _logger.Info("{0} | Conectando...", _device.IpAddress);
                bool bIsConnected = false;
                
                bIsConnected = _zkDevice.Connect_Net(_device.IpAddress, _device.IpPort);

                if (bIsConnected == true)
                {

                    //iMachineNumber = 1;//In fact,when you are using the tcp/ip communication,this parameter will be ignored,that is any integer will all right.Here we use 1.
                    //axCZKEM1.RegEvent(iMachineNumber, 65535);//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
                    _device.Status = DeviceStatus.Online;
                    _logger.Info("{0} | Conectando...[OK]", _device.IpAddress);
                }
                else
                {
                    _device.Status = DeviceStatus.Offline;
                    int idwErrorCode = 0;
                    _zkDevice.GetLastError(ref idwErrorCode);
                    string errorMessage = "Error de conexión,ErrorCode=" + idwErrorCode.ToString();
                    throw new ApplicationException(errorMessage);
                }

                //_zkDevice.Disconnect();
            }
            catch (Exception ex)
            {
                _logger.Error("{0} | Obteniendo estado del dispositivo...[FALLO]: {1}", _device.IpAddress, ex.Message);
                _device.StatusMessage = ex.Message;
            }
        }
    }
}
